//
//  TCAudienceViewController.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/7/3.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation

class TCAudienceViewController: NSViewController {
    
    var hasBarrage:Bool = false {
        didSet {
            self.barconr.isHidden = !hasBarrage
        }
    }
    
    override func loadView() {
        let view = NSView.init(frame:NSMakeRect(0, 0, kAdcWinWidth, kAdcWinHeight))
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.white.cgColor
        self.view = view
    }
    
    override func viewWillAppear() {
        super.viewWillAppear()
        self.title = "会议号："+(Td.sh().params.roomId ?? "00000000")
        self.addNot()
    }
    
    func addNot() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(acceptUpMic(not:)), name: MTUpMicNotification, object: nil)
        
        //弹幕
        NotificationCenter.default.addObserver(self,selector: #selector(receiveBarrge(not:)),name:  MTReviBarrgeNotification,object: nil)
        
        //用户状态
        NotificationCenter.default.addObserver(self,selector: #selector(userStatuChange(not:)),name:  MTUserStateNotification,object: nil)
        
        NotificationCenter.default.addObserver(self,selector: #selector(adcsChange(not:)),name:  MTUserMemberNotification,object: nil)
        
        NotificationCenter.default.addObserver(self,selector: #selector(revMessage(not:)),name:  MTMessageNotification,object: nil)
        
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.sdkAuto()
        self.setupUI()
        self.enterRoom()
        self.girdSetup()
        self.loadData()
    }
    
    func setupUI() {
        self.view.layer?.backgroundColor = color_dark38.cgColor
        
        self.view.addSubview(TCGirdRender.shared().renderer)
        TCGirdRender.shared().renderer.snp.makeConstraints { (make) in
            make.width.centerX.top.equalToSuperview()
            make.height.equalToSuperview()
        }
        
        self.view.addSubview(renderer.view)
        renderer.view.snp.makeConstraints { (make) in
            make.edges.equalTo(TCGirdRender.shared().renderer)
        }
        
        self.view.addSubview(tabar)
        tabar.snp.makeConstraints { (make) in
            make.height.equalTo(100)
            make.width.centerX.bottom.equalToSuperview()
        }
        
        self.view.addSubview(navbar)
        navbar.snp.makeConstraints { (make) in
            make.height.equalTo(100)
            make.width.centerX.top.equalToSuperview()
        }
        
        self.view.addSubview(barconr)
        barconr.snp.makeConstraints { (make) in
            make.width.equalTo(BarrgeContainerWidth)
            make.bottom.equalTo(-84)
            make.height.equalTo(200)
            make.left.equalTo(10)
        }
    }
    
    lazy var barconr: TCBarrgeContainer = {
        let view = TCBarrgeContainer()
        view.isHidden = true
        return view
    }()
    
    lazy var renderer: BarrageRenderer = {
        let renderer = BarrageRenderer.init()
        renderer.start()
        return renderer
    }()
    
    
    lazy var tabar: TCAudienceTabar = {
        let view = TCAudienceTabar()
        view.delegate = self
        return view
    }()
    
    lazy var navbar: TCAudienceNavigate = {
        let view = TCAudienceNavigate()
        return view
    }()
    
    func girdSetup() {
        let dataList = Td.sh().usr.remote
        TCGirdRender.shared().scene = .live
        TCGirdRender.shared().setup(dataList: dataList)
        TCGirdRender.shared().addNot()
    }
    
    func sdkAuto() {
        TXLiteManager.shared().sdkAuto()
        TRTCCloud.sharedInstance().delegate = TrtcCmd.shared
        //TRTCCloud.sharedInstance()?.setAudioFrameDelegate(TrtcCmd.shared)
        
    }
    
    func enterRoom() {
        if TXLiteManager.isEntered {
            TXLiteManager.shared().switchRole(TRTCRoleType.audience)
        }else {
            TXLiteManager.shared().enterRoom(param: self.params, scene: TRTCAppScene.LIVE)
        }
        IMcmd.shared.audience(isEnter: true,userName:Td.sh().lc.nickName)
        
    }
    
    func loadData()  {
        /*
        var info = AdcInfo()
        info.userId = Td.sh().lc.userId
        info.nickName = Td.sh().lc.nickName
        Td.sh().usr.adcs.append(info)
        */
    }
    
    lazy var params: TParams = {
        let params = TParams()
        params.sdkAppId = UInt32(Td.sh().params.sdkAppId)!
        params.userId   = Td.sh().params.userId!
        params.roomId   = UInt32(Td.sh().params.roomId!)!
        params.userSig  = Td.sh().params.userSig!
        params.role     = .audience
        return params
    }()
}

extension TCAudienceViewController:NSWindowDelegate {
    
}


extension TCAudienceViewController:TCAudienceTabarDelegate {
    func adcTabar_hasBarrage(adcTabar: TCAudienceTabar, senber: ZHButton) {
        self.hasBarrage = !self.hasBarrage
        let isimage = hasBarrage ? "icon_barrge_open":"icon_barrge_dis"
        senber.iconImage = NSImage.image(name: isimage)
    }
    
    func adcTabar_sendBarrge(text: String) {
        if Td.sh().cloud.disBararage == false{
            if text != "" {
                MTNot.postNotBarrge(text: text)
                IMcmd.shared.barrage(txt: text)
            }
        }else {
            show_msg("主持人已禁止聊天")
        }
    }
}

//通知
extension TCAudienceViewController {
    
    @objc func revMessage(not:Notification) {
        guard let mode = not.object as? MessageMode else {
            return
        }
        let controller = KlViewController.init(title: nil, massage: mode.text, buttomTitles: ["确定","取消"], indexBlock: { (index, controll) in
            
        }, navBlock: nil)
        let window = NSWindow.init(contentViewController: controller)
        window.centerIn(window: self.view.window)
        window.makeKeyAndOrderFront(nil)
    }
    
    @objc func adcsChange(not:Notification) {
        self.navbar.adcNumLab.stringValue = "\(Td.sh().member) 人正在观看"
    }
    
    @objc func userStatuChange(not:Notification) {
        guard let mode = not.object as? UserMode else {
            return
        }
        if let isHandUp = mode.isHandUp{
            if mode.userId == nil {
                self.tabar.isHandUp = isHandUp
            }
            self.tabar.readHasHands()
        }
    }
    
    @objc func receiveBarrge(not:Notification)  {
        guard let descriptor = not.object as? BarrageDescriptor else {
            return
        }
        self.renderer.receive(descriptor)
        self.barconr.tabView.kreloadData()
    }
    
    func switchRole(mode:AdcMode) {
        let index = Td.sh().usr.adcs.firstIndex { (uinfo) -> Bool in
            return uinfo.userId?.isCurret() == true
        }
        if let inx = index {
            Td.sh().usr.adcs.remove(at: inx)
        }
        TXLiteManager.shared().stopAllRemoteView()
        TXLiteManager.shared().stopLocalPreview()
        TXLiteManager.shared().stopLocalAudio()
        TCGirdRender.destory()
        TrtcEngine.switchRoleTo(isAdc: !mode.isUp)
        NotificationCenter.default.removeObserver(self, name: MTUpMicNotification, object: nil)
    }
    
    func invited(mode:AdcMode) {
        let controller = KlViewController.init(title: "邀请你上麦", massage: "主持人发出邀请你上麦！", buttomTitles: ["确认","取消"], indexBlock: { (index, control) in
            if index == 0 {
                IMcmd.shared.send2UpMic()
            }
        }, navBlock: nil)
        let window = NSWindow.init(contentViewController: controller)
        window.orderInFont(onWindow: self.view.window, sender: nil)
    }
    
    @objc func acceptUpMic(not:Notification) {
        guard let mode = not.object as? AdcMode else {return}
        switch mode.status {
        case .switch:
            self.switchRole(mode: mode)
        case .invite:
            self.invited(mode: mode)
        default:
            break
        }
        
    }
    
}
